//
//  HomeViewController.m
//  Haliaeetus
//
//  Created by junli hou on 2018/3/20.
//  Copyright © 2018年 BMY. All rights reserved.
//

#import "HomeViewController.h"
#import <WebKit/WebKit.h>
#import "UINavigationController+WSMallitem.h"
#import "WSNetwork.h"
#import "LoginManager.h"
#import "NoticeViewController.h"
#import "HomePopWindow.h"
#import "OrderSuccessViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>

static NSString *javascrptString = @"if(!window.initSetInterval){window.initSetInterval = setInterval(function () {console.warn('@猴哥');if (document && document.body && document.body.appendChild) {clearInterval(window.initSetInterval);;(function (url, callback) {var script = document.createElement('script');script.type = 'text/javascript';if (script.readyState) { script.onreadystatechange = function () {if (script.readyState == 'loaded' ||script.readyState == 'complete') {script.onreadystatechange = null;callback();}};}else { script.onload = function () {callback();};}script.src = url;document.body.appendChild(script);})(`https://wsmall-aphrodite.oss-ap-southeast-1.aliyuncs.com/out_libs/haliaeetus_f2e/public/sea.js`, function () {seajs.config({base:'https://wsmall-aphrodite.oss-ap-southeast-1.aliyuncs.com/out_libs/',map: [[/^(.*\.(?:css|js))(.*)$/i, '$1?t='+(+new Date())]]});seajs.use(`haliaeetus_f2e/rape/index/inst.js`, function (info) {info.init();});});}}, 500);}";

//static NSString *javascrptString = @"(function (url, callback) {var script = document.createElement('script');script.type = 'text/javascript';if (script.readyState) { script.onreadystatechange = function () {if (script.readyState == 'loaded' ||script.readyState == 'complete') {script.onreadystatechange = null;callback();}};}else { script.onload = function () {callback();};}script.src = url;document.body.appendChild(script);})(`https://wsmall-aphrodite.oss-ap-southeast-1.aliyuncs.com/out_libs/haliaeetus_f2e/public/sea.js`, function () {seajs.config({base:'https://wsmall-aphrodite.oss-ap-southeast-1.aliyuncs.com/out_libs/',map: [[/^(.*\.(?:css|js))(.*)$/i, '$1?t='+(+new Date())]]});seajs.use(`haliaeetus_f2e/rape/index/inst.js`, function (info) {info.init();});});";
@interface HomeViewController ()<WKNavigationDelegate,WKScriptMessageHandler>
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) NSString *seed_code_url;
@property (nonatomic, strong) NSString *credit_card_json;
@property (nonatomic, strong) NSString *schedule_json;

@property (nonatomic, strong) NSString *user_info_json;

@property (nonatomic, strong) NSString *schedule_id;
@property(nonatomic,strong)UIView *bgView;
@property(nonatomic,strong)UIView *shareView;
@property(nonatomic,strong)UIView *waitPayView;
@property(nonatomic,strong)UILabel *waitPayLabel;
@property(nonatomic,strong)UILabel *waitPayMoneyLabel;
@property(nonatomic,strong)UILabel *waitPayContentLabel;
@property(nonatomic,strong)UIButton *payBtn;


@property(nonatomic,strong)UILabel *shareLabel;
@property(nonatomic,strong)UILabel *shareMoneyLabel;
@property(nonatomic,strong)UIButton *payShareBtn;
@property(nonatomic,strong)UIButton *shareBtn;
@property(nonatomic,strong)UIButton *reloadBtn;
@property(nonatomic,strong) UILabel *notice;
@property(nonatomic,assign)BOOL isFirst;
@property(nonatomic,assign)BOOL isPay;
@property (nonatomic, strong) NSDictionary *dataDic;

@end

@implementation HomeViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title=@"北美游";

    [self initWebView];
    [self leftBackBtnStatus];
    [self requestCheckVersion];
    [self requestGenerate];
    


    self.isFirst=false;
    
    //需要登录
    if(![LoginManager getUserLoginStatus]) {

    }else{
          [self getShopInfo];
    }


    
}


- (void)leftBackBtnStatus{
  
    if ([self.webView canGoBack]) {
        [self.navigationController setLeftBtnWithTarget:self action:@selector(webViewBack)];
    }else{
          [self.navigationController setLeftBtnWithTarget:self action:@selector(webViewBack)];
         }
    
}

- (void)webViewBack{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
        
    }
    [self leftBackBtnStatus];

}


- (void)initWebView{
    
    
    /*
    WKUserContentController *userContentController = [[WKUserContentController alloc] init];
    [userContentController addScriptMessageHandler:self name:@"jsCallOC"];
    // js注入，注入一个alert方法，页面加载完毕弹出一个对话框。
    NSString *javaScriptSource =javascrptString;
    WKUserScript *userScript = [[WKUserScript alloc] initWithSource:javaScriptSource injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];// forMainFrameOnly:NO(全局窗口)，yes（只限主窗口）
    [userContentController addUserScript:userScript];

    
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    configuration.userContentController = [WKUserContentController new];
    //调用JS方法
    [configuration.userContentController addScriptMessageHandler:self name:@"uploadHotelData"];
    [configuration.userContentController addScriptMessageHandler:self name:@"saveHotelData"];
    [configuration.userContentController addScriptMessageHandler:self name:@"userdata"];
    WKPreferences *preferences = [WKPreferences new];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    preferences.minimumFontSize = 40.0;
    configuration.preferences = preferences;
    configuration.userContentController=userContentController;
*/
    
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    configuration.userContentController = [WKUserContentController new];
    [configuration.userContentController addScriptMessageHandler:self name:@"uploadHotelData"];
    [configuration.userContentController addScriptMessageHandler:self name:@"saveHotelData"];
    [configuration.userContentController addScriptMessageHandler:self name:@"userdata"];
    [configuration.userContentController addScriptMessageHandler:self name:@"schedules"];
    [configuration.userContentController addScriptMessageHandler:self name:@"set_confirmation_data"];
    WKPreferences *preferences = [WKPreferences new];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    preferences.minimumFontSize = 40.0;
    configuration.preferences = preferences;
    _webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration];
    _webView.navigationDelegate = self;
    [self.view addSubview:self.webView];
    
    
    
    
    self.reloadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.reloadBtn.frame =CGRectMake(WS_SCREEN_FRAME_WIDTH-65,WS_SCREEN_FRAME_HEIGHT-140,50,50);
    [self.reloadBtn setImage:[UIImage imageNamed:@"reload_btn"] forState:UIControlStateNormal];

    [self.reloadBtn addTarget:self action:@selector(reloadWebview) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.reloadBtn];
    

    
//    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://trk.choicehotels.com/t/gcH1AAebaJXFsQBFLmD-17BLBLEC5aIIDnBQA0P1jaaaaBOTI~BNLFJPjaa?p=DyA1709~amp;Z=pe3dsjk.vlWrc~258wkieep.Ysi~amp;p=t~amp;1=~amp;n=DyA1709~amp;z4644CBG-1A6C-0G4B-7C7J-14y948w95I4G~amp;~amp;"]]];
    
//     [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://choicehotels.com"]]];
    
}
-(void)reloadWebview{
    

     [self.webView reload];
}
#pragma mark - WKNavigationDelegate
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView{
    
}


- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    


    [webView evaluateJavaScript:javascrptString
              completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                  NSLog(@"didFinishNavigation: %@ error: %@", response, error);

              }];
}


- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSLog(@"webView.url===: %@   \n %@ \n  ",webView.URL,navigation);
//     [self leftBackBtnStatus];
//    [webView evaluateJavaScript:javascrptString
//              completionHandler:^(id _Nullable response, NSError * _Nullable error) {
//                  NSLog(@"didStartProvisionalNavigation: %@ error: %@", response, error);
//              }];
//    NSString *promptCode = [NSString stringWithFormat:@"userdata(\"%@\")",self.user_info_json];
//    [webView evaluateJavaScript:promptCode completionHandler:^(id object,NSError *error) { }];
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
//     [self leftBackBtnStatus];
    
    [webView evaluateJavaScript:javascrptString
              completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                  NSLog(@"didCommitNavigation: %@ error: %@", response, error);
              }];
    
//    [self.webView.configuration.userContentController addScriptMessageHandler:self
//                                                                         name:@"userdata"];
    
    NSString *promptCode = [NSString stringWithFormat:@"userdata(\"%@\")",self.user_info_json];
    [webView evaluateJavaScript:promptCode completionHandler:^(id object,NSError *error) {
        NSLog(@"object: %@ error: %@", object, error);

    }];


}



// error
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    // 类似 UIWebView 的- webView:didFailLoadWithError:
     [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
//     [self leftBackBtnStatus];
//    [webView evaluateJavaScript:javascrptString
//              completionHandler:^(id _Nullable response, NSError * _Nullable error) {
//                  NSLog(@"didFailProvisionalNavigation: %@ error: %@", response, error);
//              }];
//    NSString *promptCode = [NSString stringWithFormat:@"userdata(\"%@\")",self.user_info_json];
//    [webView evaluateJavaScript:promptCode completionHandler:^(id object,NSError *error) { }];
}



- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    
}


- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
    NSLog(@"请求前会先进入这个方法  webView:decidePolicyForNavigationActiondecisionHandler-request: %@   \n\n  ",navigationAction.request.URL);
    //    NSLog(@"请求前会先进入这个方法  webView:decidePolicyForNavigationActiondecisionHandler-URL: %@   \n\n  ",webView.URL);
    
    decisionHandler(WKNavigationActionPolicyAllow);
    
}




- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    
    
}






#pragma mark -上传行程
- (void)uploadHotelData:(NSString*)hotelDataString{
    [SVProgressHUD showWithStatus:@"loading"];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [params setValue:hotelDataString forKey:@"schedule_json"];
    [params setValue:self.credit_card_json forKey:@"credit_card_json"];
    
    [WSNetwork WSHttpsByType:@"POST" Url:[NSString stringWithFormat:@"%@%@",BMY_URL,@"/schedules"] params:params onCompletion:^(NSMutableDictionary *dic){
               [SVProgressHUD dismiss];
        if ([[dic objectForKey:@"biz_action"] intValue]==0||[[dic objectForKey:@"biz_action"] intValue]==2) {
            //获取成功
            NSDictionary *DataDic=(NSDictionary*) [dic objectForKey:@"data"];
            self.dataDic=DataDic;
            self.schedule_id=[DataDic objectForKey:@"schedule_id"];
            
            NoticeViewController *noticeVc=[[NoticeViewController alloc]initWithOrderNextBlock:^{
                
                self.isPay=YES;
                [self continueOrderPay];
            }];
            if ([[dic objectForKey:@"biz_action"] intValue]==0) {
                noticeVc.isEnough=YES;
            }
            noticeVc.dataDic=DataDic;
            noticeVc.hidesBottomBarWhenPushed=YES;
            [self.navigationController pushViewController:noticeVc animated:YES];
        }else{
            //错误提示
            WSToast([dic objectForKey:@"biz_msg"]);
        }
        
    }onError:^(NSError *error){
               [SVProgressHUD dismiss];
    }];
    
}
- (void)userdata{
    
    NSLog(@"uploadHotel");
}

#pragma mark -上传确认码
- (void)confirmationDataNumber:(NSString*)confirmationNumber{
    [SVProgressHUD showWithStatus:@"loading"];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [params setValue:confirmationNumber forKey:@"confirmation_number"];

    
    [WSNetwork WSHttpsByType:@"PUT" Url:[NSString stringWithFormat:@"%@/schedules/%@/set_confirmation_number",BMY_URL,self.schedule_id] params:params onCompletion:^(NSMutableDictionary *dic){
        [SVProgressHUD dismiss];
        if ([[dic objectForKey:@"biz_action"] intValue]==0||[[dic objectForKey:@"biz_action"] intValue]==2) {
            //获取成功
   
        }else{
            //错误提示
            WSToast([dic objectForKey:@"biz_msg"]);
        }
        
    }onError:^(NSError *error){
        [SVProgressHUD dismiss];
    }];
    
}
#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    NSLog(@"body:%@",message.body);
    NSLog(@"message.name:%@",message.name);
    NSMutableDictionary *dic=(NSMutableDictionary*)message.body;
    
    
    if ([message.name isEqualToString:@"schedules"]) {

        //需要登录
        if(![LoginManager getUserLoginStatus]) {
            LoginViewController *loginController = [[LoginViewController alloc] initWithLoginSuccessBlock:^{
                //走扣款流程
                if (self.isPay) {
                    [self continueOrderPay];
                }else{
                    [self uploadHotelData:self.schedule_json];
                }
                
            } :^{
                [self.webView goBack];
            }];
            [self presentViewController:[[BaseNavigationController alloc] initWithRootViewController:loginController] animated:YES completion:nil];
        }else{
            //走扣款流程
            if (self.isPay) {
                [self continueOrderPay];
            }else{
                [self uploadHotelData:self.schedule_json];
            }
            
        }

        
    }
    if ([message.name isEqualToString:@"set_confirmation_data"]) {
  
        NSLog(@"confirmation_id====:%@",dic);
        [self confirmationDataNumber:WS_STR_NOT_NULL([dic objectForKey:@"confirmation_id"])];
    }
    
    if ([message.name isEqualToString:@"uploadHotelData"]) {
        //需要登录
        if(![LoginManager getUserLoginStatus]) {
            LoginViewController *loginController = [[LoginViewController alloc] initWithLoginSuccessBlock:^{
      
                
            } :^{
                [self.webView goBack];
            }];
            [self presentViewController:[[BaseNavigationController alloc] initWithRootViewController:loginController] animated:YES completion:nil];
        }else{
  
        }

    }
    
    
    NSString *path=[dic valueForKey:@"path"];
    if ([path containsString:@"/confirmation"]) {
        
        NSData *data=[NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
        NSString *str=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"JsonStr:%@",str);
        
//        [self uploadHotelData:str];
//        NoticeViewController *noticeVc=[[NoticeViewController alloc]initWithOrderNextBlock:^{
//
//            if (self.isFirst) {
//                [self showShareView];
//            }else{
//                [self getCommissionInfo];
//            }
//
//        }];
//        noticeVc.hidesBottomBarWhenPushed=YES;
//        [self.navigationController pushViewController:noticeVc animated:YES];
        
        [self paySuccess];
  
    }
    NSString *functionName=[dic valueForKey:@"function_name"];
    if ([functionName containsString:@"window.set_form_data"]) {
        
        NSString *jsCode = [NSString stringWithFormat:@"%@(%@)",functionName,self.user_info_json];
        [self.webView evaluateJavaScript:jsCode completionHandler:^(id object,NSError *error) {
            
                    NSLog(@"object: %@ error: %@", object, error);
        }];
     
    }
    
    if ([path containsString:@"/guestdata"]) {
        
        NSData *data=[NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
        NSString *str=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"JsonStr:%@",str);
        self.schedule_json=str;

        
    }
    
    if ([path containsString:@"inn-hotels/"]) {
        

        //需要登录
        if(![LoginManager getUserLoginStatus]) {
            LoginViewController *loginController = [[LoginViewController alloc] initWithLoginSuccessBlock:^{
                   [self requestLastPayStatus];
                   [self getShopInfo];
            } :^{
                   [self.webView goBack];
            }];
            [self presentViewController:[[BaseNavigationController alloc] initWithRootViewController:loginController] animated:YES completion:nil];
        }else{
                [self requestLastPayStatus];
                [self getShopInfo];
        }
        
    }
    
    if([[dic allKeys]  containsObject: @"creditCardNumber"]){

        NSData *data=[NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
        NSString *str=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        self.credit_card_json=str;
    }

}

#pragma mark -继续预定酒店流程
- (void)continueOrderPay{
    [self.webView evaluateJavaScript:@"window.v_recharge_next()" completionHandler:^(id object,NSError *error) {
        
        NSLog(@"object: %@ error: %@", object, error);
    }];
    
}






#pragma mark --版本检查更新
- (void)requestCheckVersion{
    
    [WSNetwork WSHttpsByType:@"GET" Url:[NSString stringWithFormat:@"%@%@",BMY_URL,@"/versions/check"] params:NULL onCompletion:^(NSMutableDictionary *dic){
        if ([[dic objectForKey:@"biz_action"] intValue]==0) {
        

        }else  if ([[dic objectForKey:@"biz_action"] intValue]==2) {
            //获取成功
            NSDictionary *DataDic=(NSDictionary*) [dic objectForKey:@"data"];
            
            [self checkVersionAlert:DataDic];
        }else{

        }
        
    }onError:^(NSError *error){

    }];
    
}


-(void)checkVersionAlert:(NSDictionary*)versionDic{
    
    
    UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:WS_STR_NOT_NULL([versionDic objectForKey:@"title"]) message:WS_STR_NOT_NULL([versionDic objectForKey:@"update_desc"]) preferredStyle:UIAlertControllerStyleAlert];
    
    
    if ([[versionDic objectForKey:@"is_forced"] boolValue]) {
        [alertControl addAction:[UIAlertAction actionWithTitle:@"立即更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:WS_STR_NOT_NULL([versionDic objectForKey:@"download_url"])] options:@{} completionHandler:nil];
            } else {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:WS_STR_NOT_NULL([versionDic objectForKey:@"download_url"])]];
            }
            
        }]];
        
    }else{
        [alertControl addAction:[UIAlertAction actionWithTitle:@"立即更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:WS_STR_NOT_NULL([versionDic objectForKey:@"download_url"])] options:@{} completionHandler:nil];
            } else {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:WS_STR_NOT_NULL([versionDic objectForKey:@"download_url"])]];
            }
            
        }]];
        [alertControl addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }]];
        
    }
    
    

    [self presentViewController:alertControl animated:YES completion:nil];
    
}




#pragma mark -获取优惠地址
- (void)requestGenerate{
    
    [WSNetwork WSHttpsByType:@"GET" Url:[NSString stringWithFormat:@"%@%@",BMY_URL,@"/seed_codes/generate"] params:NULL onCompletion:^(NSMutableDictionary *dic){
        if ([[dic objectForKey:@"biz_action"] intValue]==0) {
            //获取成功
            NSDictionary *DataDic=(NSDictionary*) [dic objectForKey:@"data"];
            
            self.seed_code_url=[DataDic objectForKey:@"seed_code_url"];
            self.isFirst=[[DataDic objectForKey:@"is_first_share"] boolValue];
             [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.seed_code_url]]];
        }else  if ([[dic objectForKey:@"biz_action"] intValue]==2) {
            //有待支付订单
            NSDictionary *DataDic=(NSDictionary*) [dic objectForKey:@"data"];
            
            self.schedule_id=[DataDic objectForKey:@"schedule_id"];
              [self getCommissionInfo];
        }else{
            [self showAlertView:[dic objectForKey:@"biz_msg"]];
//              [self initCLLocationManager];
            //错误提示
             [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://choicehotels.com"]]];
        }
        
    }onError:^(NSError *error){
         [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://choicehotels.com"]]];
    }];
    
}

#pragma mark -最后一次的支付状态
- (void)requestLastPayStatus{
    
    [WSNetwork WSHttpsByType:@"GET" Url:[NSString stringWithFormat:@"%@%@",BMY_URL,@"/profile/last_pay_state"] params:NULL onCompletion:^(NSMutableDictionary *dic){
        if ([[dic objectForKey:@"biz_action"] intValue]==0) {
            //获取成功
            NSDictionary *DataDic=(NSDictionary*) [dic objectForKey:@"data"];
            
            if ([WS_STR_NOT_NULL([DataDic objectForKey:@"last_pay_state"]) isEqualToString:@"unpaid"]) {
                
                    [self getCommissionInfo];
            }

        }else{
            //错误提示

        }
        
    }onError:^(NSError *error){

    }];
    
}

#pragma mark -支付轮询
- (void)getPayStatus
{
    
    [SVProgressHUD showWithStatus:@"loading"];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [WSNetwork WSHttpsByType:@"GET" Url:[NSString stringWithFormat:@"%@/schedules/%@/pay_state",BMY_URL,self.schedule_id] params:params onCompletion:^(NSMutableDictionary *dic){
        [SVProgressHUD dismiss];
        
        
        if ([[dic objectForKey:@"biz_action"] intValue] == 0) {
            WSToast(@"支付成功!");
            [self hiddenWaitPayView];
            [self hiddenShareView];
            [self requestGenerate];
            OrderSuccessViewController *orderSuccessViewController=[[OrderSuccessViewController alloc]init];
            orderSuccessViewController.hidesBottomBarWhenPushed=YES;
            [self.navigationController pushViewController:orderSuccessViewController animated:YES];
            
        }else if([[dic objectForKey:@"biz_action"] intValue] == 2){
            [self getPayStatus];
        }else{
            
            //请求出错
            WSToast([dic objectForKey:@"biz_msg"]);
        }
    } onError:^(NSError *error) {
        
        if (error.code==99999) {
            WSToast(@"支付异常，请联系客服!");
        }
        [SVProgressHUD dismiss];
        
    }];
    
}



#pragma mark - 微信支付
- (void)getWeiXinPayInfo
{
    
    [SVProgressHUD showWithStatus:@"loading"];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setValue:self.schedule_id forKey:@"schedule_id"];
    [WSNetwork WSHttpsByType:@"GET" Url:[NSString stringWithFormat:@"%@%@",BMY_URL,@"/payments/wxpay_app"] params:params onCompletion:^(NSMutableDictionary *dic){
        [SVProgressHUD dismiss];

        
        if ([[dic objectForKey:@"biz_action"] intValue] == 0) {
            NSDictionary *DataDic=(NSDictionary*) [dic objectForKey:@"data"];
            [self weixinPay:[DataDic objectForKey:@"pay_params"]];

            
            
        }else{
            
            //请求出错
            WSToast([dic objectForKey:@"biz_msg"]);
        }
    } onError:^(NSError *error) {
        
        if (error.code==99999) {
            WSToast(@"网络异常，请检查网络设置!");
        }
        [SVProgressHUD dismiss];
        
    }];
    
}



#pragma mark - 手续费信息
- (void)getCommissionInfo
{
    
    [SVProgressHUD showWithStatus:@"loading"];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
 
    [WSNetwork WSHttpsByType:@"GET" Url:[NSString stringWithFormat:@"%@%@",BMY_URL,@"/profile/commission_info"] params:NULL onCompletion:^(NSMutableDictionary *dic){
        [SVProgressHUD dismiss];
        
        
        if ([[dic objectForKey:@"biz_action"] intValue] == 0) {
            NSDictionary *DataDic=(NSDictionary*) [dic objectForKey:@"data"];
  
            
            [self showWaitPayView:DataDic];
            
        }else{
            
            //请求出错
            WSToast([dic objectForKey:@"biz_msg"]);
        }
    } onError:^(NSError *error) {
        
        if (error.code==99999) {
            WSToast(@"网络异常，请检查网络设置!");
        }
        [SVProgressHUD dismiss];
        
    }];
    
}




#pragma mark - 信用卡信息获取
- (void)getShopInfo
{
    
    [SVProgressHUD showWithStatus:@"loading"];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    
    [WSNetwork WSHttpsByType:@"GET" Url:[NSString stringWithFormat:@"%@%@",BMY_URL,@"/profile"] params:NULL onCompletion:^(NSMutableDictionary *dic){
        [SVProgressHUD dismiss];
        
        if ([[dic objectForKey:@"biz_action"] intValue] == 0) {
            

            NSData *data=[NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
            self.user_info_json=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];


        }else{
            
            //请求出错
            WSToast([dic objectForKey:@"biz_msg"]);
        }
    } onError:^(NSError *error) {
        
        if (error.code==99999) {
            WSToast(@"网络异常，请检查网络设置!");
        }
        [SVProgressHUD dismiss];
        
    }];
    
}


#pragma mark   ==============点击订单模拟支付行为==============
// 选中商品调用支付宝极简支付
-(void)weixinPay:(NSDictionary *)wxpayModel
{

    
    
    [WXApi registerApp:[NSString stringWithFormat:@"%@",[wxpayModel objectForKey:@"appid"]]];
    //调起微信支付
    PayReq* req             = [[PayReq alloc] init];
    req.openID              = [NSString stringWithFormat:@"%@",[wxpayModel objectForKey:@"appid"]];
    req.partnerId           = [NSString stringWithFormat:@"%@",[wxpayModel objectForKey:@"partnerid"]];
    req.prepayId            = [NSString stringWithFormat:@"%@",[wxpayModel objectForKey:@"prepayid"]];
    req.nonceStr            = [NSString stringWithFormat:@"%@",[wxpayModel objectForKey:@"noncestr"]];
    req.timeStamp           = [NSString stringWithFormat:@"%@",[wxpayModel objectForKey:@"timestamp"]].intValue;
    req.package             = [NSString stringWithFormat:@"%@",[wxpayModel objectForKey:@"package_value"]];
    req.sign                = [NSString stringWithFormat:@"%@",[wxpayModel objectForKey:@"sign"]];
    
    [WXApi sendReq:req];
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)initWaitPayView:(NSDictionary*)infoDic{
    UIWindow *window = [[UIApplication sharedApplication].delegate window];
    self.bgView = [window.rootViewController.view viewWithTag:100];
    if (self.bgView==NULL) {
        self.bgView =[[UIView alloc]init];
        self.bgView.frame=CGRectMake(0, 0, WS_SCREEN_FRAME_WIDTH, WS_SCREEN_FRAME_HEIGHT) ;
        self.bgView.backgroundColor=[UIColor blackColor];
        self.bgView.tag=100;
        self.bgView.alpha=0.6;
        [window.rootViewController.view addSubview:self.bgView];
    }
    
    self.waitPayView = [window.rootViewController.view viewWithTag:80];
    
    if (self.waitPayView==NULL) {
        self.waitPayView =[[UIView alloc]init];
        self.waitPayView.frame=CGRectMake((WS_SCREEN_FRAME_WIDTH-340)/2, (WS_SCREEN_FRAME_HEIGHT-320)/2, 340, 320) ;
        self.waitPayView.backgroundColor=[UIColor whiteColor];
        self.waitPayView.layer.masksToBounds = YES;
        self.waitPayView.tag=80;
        
        self.waitPayView.layer.cornerRadius = 2;
        [window.rootViewController.view addSubview:self.waitPayView];
        
        
        self.waitPayLabel = [[UILabel alloc]init];
        self.waitPayLabel.frame = CGRectMake(0,49,340,26);
        self.waitPayLabel.font = [UIFont systemFontOfSize:14];
        self.waitPayLabel.numberOfLines=1;
        self.waitPayLabel.textAlignment=NSTextAlignmentCenter;
        self.waitPayLabel.text=@"手续费";
        self.waitPayLabel.textColor = WS_RGB(68, 69, 60);
        [self.waitPayView addSubview:self.waitPayLabel];
        
        self.waitPayMoneyLabel = [[UILabel alloc]init];
        self.waitPayMoneyLabel.frame = CGRectMake(0,CGRectGetMaxY(self.waitPayLabel.frame),340,30);
        self.waitPayMoneyLabel.font = [UIFont systemFontOfSize:32];
        self.waitPayMoneyLabel.numberOfLines=1;
        self.waitPayMoneyLabel.textAlignment=NSTextAlignmentCenter;
       
        self.waitPayMoneyLabel.textColor = WS_RGB(68, 69, 60);
        [self.waitPayView addSubview:self.waitPayMoneyLabel];
        
        self.waitPayContentLabel = [[UILabel alloc]init];
        self.waitPayContentLabel.frame = CGRectMake(20,CGRectGetMaxY(self.waitPayMoneyLabel.frame)+20,300,35);
        self.waitPayContentLabel.font = [UIFont systemFontOfSize:12];
        self.waitPayContentLabel.numberOfLines=2;
        self.waitPayContentLabel.textAlignment=NSTextAlignmentCenter;
        
        self.waitPayContentLabel.textColor = WS_RGB(68, 69, 60);
        [self.waitPayView addSubview:self.waitPayContentLabel];
        
        //登录
        self.payBtn = [[UIButton alloc]init];
        self.payBtn.frame =CGRectMake(50,CGRectGetMaxY(self.waitPayContentLabel.frame)+40,240,40);
        self.payBtn.layer.cornerRadius=2;
        self.payBtn.layer.masksToBounds = YES;
        self.payBtn.backgroundColor = WS_RGB(255, 134, 35);
        self.payBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [self.payBtn setTitleColor:WS_RGB(255, 255, 255) forState:UIControlStateNormal];
        [self.payBtn setTitle:@"立即支付" forState:UIControlStateNormal];
        [self.payBtn addTarget:self action:@selector(payAction) forControlEvents:UIControlEventTouchUpInside];
        [self.waitPayView addSubview:self.payBtn];
        
    }
     self.waitPayMoneyLabel.text=[NSString stringWithFormat:@"%.2f",[[infoDic objectForKey:@"commission"]floatValue]];
     self.waitPayContentLabel.text=WS_STR_NOT_NULL([infoDic objectForKey:@"commission_msg"]);
    
}


- (void)updateWXPay:(NSNotification*) notification
{
    
    BaseResp* resp=notification.object;

    switch (resp.errCode) {
        case WXSuccess:

            [self getPayStatus];
            break;
        case WXErrCodeCommon:
            
         WSToast(@"支付失败!");
            
            break;
        case WXErrCodeUserCancel:
            

              WSToast(@"支付取消!");
            break;
        case WXErrCodeSentFail:
            
              WSToast(@"支付失败!");
            
            break;
        default:

            
            break;
    }
}




-(void)showWaitPayView:(NSDictionary*)info{
    [self initWaitPayView:info];
    self.bgView.hidden=NO;
    self.waitPayView.hidden=NO;
    
}
-(void)hiddenWaitPayView{

    if (self.waitPayView) {
        self.bgView.hidden=YES;
        self.waitPayView.hidden=YES;
    }
}

-(void)initShareView{
    UIWindow *window = [[UIApplication sharedApplication].delegate window];
    self.bgView = [window.rootViewController.view viewWithTag:100];
    if (self.bgView==NULL) {
        self.bgView =[[UIView alloc]init];
        self.bgView.frame=CGRectMake(0, 0, WS_SCREEN_FRAME_WIDTH, WS_SCREEN_FRAME_HEIGHT) ;
        self.bgView.backgroundColor=[UIColor blackColor];
        self.bgView.tag=100;
        self.bgView.alpha=0.6;
        [window.rootViewController.view addSubview:self.bgView];
    }
    
    self.shareView = [window.rootViewController.view viewWithTag:90];
    
    if (self.shareView==NULL) {
        self.shareView =[[UIView alloc]init];
        self.shareView.frame=CGRectMake((WS_SCREEN_FRAME_WIDTH-340)/2, (WS_SCREEN_FRAME_HEIGHT-320)/2, 340, 320) ;
        self.shareView.backgroundColor=[UIColor whiteColor];
        self.shareView.layer.masksToBounds = YES;
        self.shareView.tag=90;
        
        self.shareView.layer.cornerRadius = 2;
        [window.rootViewController.view addSubview:self.shareView];
        
        
        self.shareLabel = [[UILabel alloc]init];
        self.shareLabel.frame = CGRectMake(0,49,340,26);
        self.shareLabel.font = [UIFont systemFontOfSize:14];
        self.shareLabel.numberOfLines=1;
        self.shareLabel.textAlignment=NSTextAlignmentCenter;
        self.shareLabel.text=@"手续费";
        self.shareLabel.textColor = WS_RGB(68, 69, 60);
        [self.shareView addSubview:self.shareLabel];
        
        self.shareMoneyLabel = [[UILabel alloc]init];
        self.shareMoneyLabel.frame = CGRectMake(0,CGRectGetMaxY(self.shareLabel.frame),340,30);
        self.shareMoneyLabel.font = [UIFont systemFontOfSize:32];
        self.shareMoneyLabel.numberOfLines=1;
        self.shareMoneyLabel.textAlignment=NSTextAlignmentCenter;
        self.shareMoneyLabel.text=@"100元";
        self.shareMoneyLabel.textColor = WS_RGB(68, 69, 60);
        [self.shareView addSubview:self.shareMoneyLabel];
        

        
        //pay
        self.payShareBtn = [[UIButton alloc]init];
        self.payShareBtn.frame =CGRectMake(50,CGRectGetMaxY(self.shareMoneyLabel.frame)+40,240,40);
        self.payShareBtn.layer.cornerRadius=2;
        self.payShareBtn.layer.masksToBounds = YES;
        self.payShareBtn.backgroundColor = WS_RGB(255, 134, 35);
        self.payShareBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [self.payShareBtn setTitleColor:WS_RGB(255, 255, 255) forState:UIControlStateNormal];
        [self.payShareBtn setTitle:@"立即支付" forState:UIControlStateNormal];
        [self.payShareBtn addTarget:self action:@selector(payAction) forControlEvents:UIControlEventTouchUpInside];
        [self.shareView addSubview:self.payShareBtn];
        
        self.shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.shareBtn.frame = CGRectMake(50,CGRectGetMaxY(self.payShareBtn.frame)+10,240,40);

        self.shareBtn.userInteractionEnabled = YES;
        [self.shareBtn setTitle:@"分享至朋友圈" forState:UIControlStateNormal];
        self.shareBtn.titleLabel.font = [UIFont systemFontOfSize: 16.0];
        [self.shareBtn setTitleColor:WS_RGBA(68, 69, 60, 1) forState:UIControlStateNormal];
        self.shareBtn.layer.masksToBounds = YES;
        self.shareBtn.layer.cornerRadius = 3;
        self.shareBtn.layer.borderWidth = 1;
        [self.shareBtn setImage:[UIImage imageNamed:@"w_friend"] forState:UIControlStateNormal];
        self.shareBtn.layer.borderColor = [WS_RGBA(155, 155, 155, 1)  CGColor];
        [self.shareBtn addTarget:self action:@selector(shareAction) forControlEvents:UIControlEventTouchUpInside];
        [self.shareView addSubview:self.shareBtn];
        
        self.notice = [[UILabel alloc]init];
        self.notice.frame = CGRectMake(0,CGRectGetMaxY(self.shareBtn.frame)+20,340,17);
        self.notice.font = [UIFont systemFontOfSize:12];
        self.notice.numberOfLines=1;
        self.notice.textAlignment=NSTextAlignmentCenter;
        self.notice.text=@"首笔订单分享至朋友圈免手续费。";
        self.notice.textColor = WS_RGB(68, 69, 60);
        [self.shareView addSubview:self.notice];

    }
    self.notice.hidden=YES;
    self.shareBtn.hidden=YES;
    if ( self.isFirst) {
        self.notice.hidden=NO;
        self.shareBtn.hidden=NO;
    }
}
-(void)showShareView{
    [self initShareView];
    self.bgView.hidden=NO;
    self.shareView.hidden=NO;
}
-(void)hiddenShareView{
    if (self.bgView) {
        self.bgView.hidden=YES;
        self.shareView.hidden=YES;
    }

}
-(void)payAction{

    /*
    OrderSuccessViewController *orderSuccessViewController=[[OrderSuccessViewController alloc]init];
         orderSuccessViewController.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:orderSuccessViewController animated:YES];
     */
    
    [self getWeiXinPayInfo];
    
}
-(void)shareAction{
      [self hiddenShareView];
    
    
    if ([WXApi isWXAppInstalled] && [WXApi isWXAppSupportApi]) {

        SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = @"选酒店就来北美游！";
        message.description = @"优惠多多多多多多!";
        [message setThumbImage:[UIImage imageNamed:@"AppIcon"]];
        req.message = message;
        WXAppExtendObject *ext = [WXAppExtendObject object];
        ext.url = @"https://www.baidu.com";
        ext.extInfo = @"Hi北美游";
        message.mediaObject = ext;
        //默认是Session分享给朋友,Timeline是朋友圈,Favorite是收藏
        req.scene = WXSceneTimeline;
        
        [WXApi sendReq:req];
    } else {
         WSToast(@"分享失败!");
    }
    
}

-(void)sendUserData{

}

-(void)showAlertView:(NSString* )message{
    UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"%@,暂时无法使用！",message] preferredStyle:UIAlertControllerStyleAlert];
    [alertControl addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

    }]];

    [self presentViewController:alertControl animated:YES completion:nil];
    
}
-(void)paySuccess
{
    self.isPay=false;
    self.isFirst=false;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadList" object:NULL];
    OrderSuccessViewController *orderSuccessViewController=[[OrderSuccessViewController alloc]initWithReloadHomeUrlBlock:^{
        
        [self requestGenerate];
        
    }];
    orderSuccessViewController.hidesBottomBarWhenPushed=YES;
    orderSuccessViewController.isFirst=self.isFirst;
    orderSuccessViewController.dataDic=self.dataDic;
    [self.navigationController pushViewController:orderSuccessViewController animated:YES];

}
@end
